require 'sinatra/base'
require 'json'
require 'date'

require './models/item'

require './handlers/base'

class ItemHandler < BaseHandler
    ## ITEM ROUTES

    put '/items/:id' do
        # p @data
        @query = {}
        @query = @data unless @data.empty? or @data.nil?
        if Integer(params[:if]) > 0
            i = Item.first({:id=>Integer(params[:id])})
            if not i.nil?
                success = true
                if @query["matchname"]
                    success = i.update({:match_name => @query["matchname"], :archived => true})
                elsif current_user.items.include? i and not @data.nil?
                    success = i.update(@query)
                end
                p i.save
                if not success
                    p item.errors
                    @r = r('Failed to update item')
                end
            end
        end
    end
 
    get '/items?' do
        # search the items table for all items matching the given parameters
        @query = {}
        @query = @data unless @data.empty? or @data.nil?
        @query = params unless params.empty?
        if @query["tags"]
            @query["tags"] = {:title=>@query["tags"]}
        elsif @query["tag"]
            @query["tags"] = {:title=>@query["tag"]}
        end
        if @query["date"]
            @query["date"] = (DateTime.parse(params["date"]).to_date..Date::today.to_date)
        end
        p @query
        @r = r(nil, Item.all(@query))
    end

    post '/items/new?' do
        # add a new item to the database connected to current_user
        if not @data.nil?
            d = Date::today.to_date
            if params["date"]
                d = DateTime.parse(params["date"]).to_date
            end
            item = Item.create(
                  :name => @data["name"], 
                  :description => @data["description"]||"",
                  :reward => Float(@data["reward"])|| 0.0,
                  :date => d,
                  :user => current_user,
                  :found => @data["found"] || false,
                  :archived => false,
                  :reported=> false)

            unless @data['tags'].nil?
                @data['tags'].each do |t|
                    if t["title"]
                        new_tag = Tag.first_or_create(:title=>t["title"])
                        item.tags << new_tag
                    end
                end
            end

            if not item.save
                p item.errors #log the errors
                @r = r(item.errors.first.first)
            else
                @r = r(nil, item)
            end
        end
    end

    delete '/items/:id' do
        item = Item.first(:id => params[:id])
        if current_user.items.include? item and item.destroy
            @r = r("That item doesn't exist!")
        else
            @r = r("You aren't allowed to do that")
        end
    end
end